/**
 * 238. 除自身以外数组的乘积
 * https://leetcode-cn.com/problems/product-of-array-except-self/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {number[]} nums
 * @return {number[]}
 */
function productExceptSelf(nums) {
  const { length } = nums;
  const lastIndex = length - 1;
  const result = new Array(length).fill(nums[0]);
  for (let i = 1; i < lastIndex; i += 1) {
    result[i] = nums[i] * result[i - 1];
  }
  let right = 1;
  for (let i = length - 1; i >= 1; i -= 1) {
    result[i] = result[i - 1] * right;
    right *= nums[i];
  }
  result[0] = right;
  return result;
}

console.log(displayBaseArray(productExceptSelf([1, 2, 3, 4])) === '[24,12,8,6]');
console.log(displayBaseArray(productExceptSelf([-1, 1, 0, -3, 3])) === '[0,0,9,0,0]');
